<script setup>
import { get } from 'lodash';
import { puzzleGameList } from '@/common/data.js';
import { getUrlParam, getTopLevelDomain, formatConfig } from '@/common/utils.js';
import { onMounted, ref } from 'vue';
import GameItem from './GItem.vue';
import FloatHome from './FloatHome.vue';
import GameMenus from './GMenus.vue';

let cur = {};

const afc = ref(null);
const afc2 = ref(null);
const afc3 = ref(null);

const showAdsPopup = ref(false);

const _loadAFC = (domId, ref, slotId) => {
  const ls = Array.isArray(ref) ? ref : [ref];
  ls.forEach((dom) => {
    if (!dom) return;
    if (cur.platform === 'GAM') {
      const boxId = `div-gpt-ad-${slotId}-0`;
      const div = document.createElement('div');
      div.id = boxId;
      const randomLs = Array.from({ length: 16 }, () =>
        Math.floor(Math.random() * 16).toString(16),
      ).join('');
      const nonceText = `nonce-${randomLs}`;
      const script = document.createElement('script');
      script.textContent = `googletag.cmd.push(function() { googletag.display('${boxId}') })`;
      script.setAttribute('nonce', nonceText);
      div.appendChild(script);
      dom.appendChild(div);
    } else {
      const load_ad_params = `<ins class="adsbygoogle" style="display:block;width:100%;height:50px" data-ad-client="ca-pub-${cur.ca_pub}" data-ad-slot="${slotId}" data-ad-format="auto" data-full-width-responsive="true" data-ad-ref="${domId}"></ins>`;
      dom.innerHTML = load_ad_params;
      window.adsbygoogle.push({});
    }
  });
};
const _loadAFG = () => {
  const ca_pub_id = `ca-pub-${cur.ca_pub}`;
  const adsScript = document.createElement('script');
  adsScript.src = `//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${ca_pub_id}`;
  adsScript.async = true;
  adsScript.crossOrigin = 'anonymous';
  adsScript.setAttribute('data-ad-client', ca_pub_id);
  adsScript.setAttribute('data-ad-frequency-hint', '30s');
  adsScript.onload = function () {
    window.adsbygoogle = window.adsbygoogle || [];
    window.adsbygoogle.push({
      preloadAdBreaks: 'on',
      sound: 'off',
    });

    window.adsbygoogle.push({
      type: 'preroll',
      name: 'app_start',
      adBreakDone: () => {},
    });
  };
  document.head.appendChild(adsScript);
};

const handleFooterClick = (type) => {
  if (type.includes('@')) return;
  window.location.href = `/${type.toLowerCase()}/index.html`;
};

const autoPopup = () => {
  if (!cur.p_slot) return;

  const timer = window.setTimeout(() => {
    if (showAdsPopup.value) {
      window.clearTimeout(timer);
      return;
    }
    showAdsPopup.value = true;
  }, 6000);
};

let fromAutoClose = false;
const handelPopupOpened = () => {
  _loadAFC('afc3', afc3.value, cur.p_slot);

  setTimeout(() => {
    const targetNode = afc3.value?.firstElementChild;
    const observer = new MutationObserver((mutationsList) => {
      for (var mutation of mutationsList) {
        if (mutation.type === 'attributes') {
          if (targetNode.getAttribute(mutation.attributeName) === 'unfilled') {
            fromAutoClose = true;
            showAdsPopup.value = false;
          }
        }
      }
    });
    observer.observe(targetNode, {
      attributes: true,
      attributeFilter: ['data-ad-status'],
    });
    setTimeout(() => {
      observer.disconnect();
    }, 3000);
  });
};
const handelPopupClose = () => {
  if (fromAutoClose) {
    fromAutoClose = false;
  }
};

onMounted(() => {
  window._adsLoaded().then(() => {
    cur = formatConfig(get(window, 'curPortalConfig', {}));
    const { s, s2, p_slot, safg_pre } = cur;

    if (s) _loadAFC('afc', afc.value, s);
    if (s2) _loadAFC('afc2', afc2.value, s2);
    if (safg_pre) _loadAFG();
    if (getUrlParam('ap') !== '0' && p_slot) autoPopup();
  });
});

const getLayoutSize = (index) => {
  const number = index + 1;
  return Math.ceil(number / 6) % 2 ? number % 6 === 1 : number % 6 === 2;
};
const chunkArray = (arr) =>
  Array.from({ length: Math.ceil(arr.length / 6) }, (_, i) => arr.slice(i * 6, i * 6 + 6));
const gameArray = chunkArray(puzzleGameList.map((item, idx) => ({ ...item, idx })));
</script>

<template>
  <div class="game-center-wrap">
    <FloatHome />

    <div class="game-content">
      <div class="advertising top" ref="afc"></div>

      <div class="game-list" v-for="(list, index) in gameArray" :key="index">
        <div class="advertising" ref="afc2" v-if="!index"></div>
        <GameItem
          v-for="game in list"
          :key="game.name"
          :game="game"
          :class="[
            'game-item',
            {
              hide: !game.name || game.hidden,
              large: getLayoutSize(game.idx),
              gap: game.idx === 5,
            },
          ]"
        />
      </div>
    </div>

    <GameMenus />

    <div class="footer">
      <div
        class="link-item"
        v-for="type in ['Privacy', 'TOS', 'Contact', '@' + getTopLevelDomain()]"
        :key="type"
        @click="handleFooterClick(type)"
      >
        {{ type }}
      </div>
    </div>

    <van-popup
      v-model:show="showAdsPopup"
      position="center"
      :close-on-click-overlay="false"
      closeable
      :lazy-render="false"
      class="ads-popup"
      @opened="handelPopupOpened"
      @close="handelPopupClose"
    >
      <div class="ads-popup--warp" ref="afc3"></div>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.game-center-wrap {
  position: relative;
  width: 100vw;
  min-height: 100vh;
  overflow-x: hidden;
  color: #fff;

  .game-content {
    width: 100%;
    padding-bottom: 20px;
    min-height: 100vh;
    overflow-x: hidden;

    .game-list {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
      padding: 0 14px;
      margin: 10px 0;

      .advertising {
        grid-column: 1 / -1;
        grid-row: 4 / 5;
        margin: 0 -14px;
      }

      .game-item {
        position: relative;
        display: flex;
        justify-content: center;
        min-height: 109px;

        &.large {
          grid-row: span 2;
          grid-column: span 2;
        }

        &.hide {
          z-index: -1;
          opacity: 0;
        }
      }
    }

    .advertising {
      width: 100vw;
    }
  }

  .footer {
    font-size: 14px;
    line-height: 30px;
    padding: 24px 0;
    text-align: center;
    background: #fff;
    color: #555;

    & > div {
      display: inline-block;
      padding: 0 10px;
      position: relative;

      &:not(&:last-child) {
        text-decoration: underline;

        &::after {
          content: '';
          display: block;
          position: absolute;
          top: 9px;
          right: 0;
          width: 1px;
          height: 14px;
          background: #555;
        }
      }
    }
  }

  .ads-popup {
    width: calc(100% - 2px);
    padding: 30px 0px 1px;
    border-radius: 10px;
    overflow: hidden;
    max-height: calc(100vh - 35px);

    &--warp {
      min-height: 312px;
    }
  }
}
</style>
<style lang="scss">
.game-center-wrap {
  .ads-popup {
    max-width: unset;

    .van-icon {
      padding: 8px;
      transform: translate(18px, -20px) scale(0.8);
    }
  }
}

.loading-dialog {
  background: none;

  .van-loading {
    overflow: hidden;
  }
}

.autoSizeSearch.van-search > div {
  padding-left: 20px;
  height: 100%;
  line-height: 100%;

  & > div {
    height: 100%;
  }
}
</style>
